package com.dragon.logical.service.avttendance.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.logical.service.avttendance.IDailyLogsService;
import com.dragon.logical.service.contract.ICommentService;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.Comment;
import com.dragon.repository.entity.DailyLogs;
import com.dragon.repository.entity.OtherFile;
import com.dragon.repository.mapper.AdminMapper;
import com.dragon.repository.mapper.DailyLogsMapper;
import com.dragon.repository.mapper.OtherFileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 日报 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-07-27
 */
@Service
public class DailyLogsServiceImpl extends ServiceImpl<DailyLogsMapper, DailyLogs> implements IDailyLogsService {

    @Autowired
    DailyLogsMapper mapper;
    @Autowired
    OtherFileMapper fileMapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    ICommentService commentService;

    @Override
    public Map<String, List<DailyLogs>> dailyList(Integer adminIds, String time, Integer type) {
        QueryWrapper<DailyLogs> wrapper = new QueryWrapper<>();
        //如果参数time没传参，默认当天
        if (StrUtil.isBlank(time)){
            time = DateUtil.format(DateUtil.date(),"yyyy-MM-dd");
        }
        wrapper.eq(adminIds != null, "a.admin_id", adminIds)
                .eq(type != null, "a.type", type)
                //.apply(StrUtil.isNotBlank(time)," date_format(create_time,'%y%mm%') = date_format('" + time + "-01','%y%mm%')")
                .apply(StrUtil.isNotBlank(time),"LEFT(a.create_time,10)= '" +time+ "'")
                .orderByDesc("a.create_time");
        List<DailyLogs> dailyLogs = mapper.selectListByWrapper(wrapper);
        dailyLogs.stream().forEach(s -> s.setJudgmentTime(DateUtil.format(s.getCreateTime(), "yyyy-MM-dd")));
        Map<String, List<DailyLogs>> collect = dailyLogs
                .stream()
                .collect(Collectors.groupingBy(DailyLogs::getJudgmentTime));
        return collect;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addDaily(DailyLogs daily, HttpServletRequest request) {
        //Integer adminId = Integer.valueOf(JwtUtil.getAdminId(request));
        daily.setCreateTime(DateUtil.date());
        //daily.setAdminId(adminId);
        mapper.insert(daily);
        if (daily.getOtherFiles() != null){
            for (OtherFile otherFile : daily.getOtherFiles()) {
                otherFile.setStreamType(0);
                otherFile.setCorrelationId(daily.getId());
                fileMapper.insert(otherFile);
            }
        }
    }

    @Override
    public void updateDaily(DailyLogs daily) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String dd = sdf.format(date);
        DailyLogs dailyLogs = mapper.selectById(daily.getId());
        String createTime = sdf.format(dailyLogs.getCreateTime());
        if (!createTime.equals(dd)) {
            throw new CustomException(ResultCode.ONLY_UPDATE_NOW_DAY_DAILY);
        }
        if (dailyLogs.getOtherFiles() != null || dailyLogs.getOtherFiles().size() != 0) {
            for (OtherFile otherFile : dailyLogs.getOtherFiles()) {
                fileMapper.deleteById(otherFile);
            }
        }
        for (OtherFile otherFile : daily.getOtherFiles()) {
            otherFile.setStreamType(0);
            otherFile.setCorrelationId(daily.getId());
            fileMapper.insert(otherFile);
        }
        mapper.updateById(daily);
    }

    @Override
    public void deleteDaily(String ids) {
        List<Integer> dailyIds = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        mapper.deleteBatchIds(dailyIds);
    }

    @Override
    public DailyLogs showDailyLogOne(Integer adminId, String nowTime) {
        QueryWrapper<DailyLogs> wrapper = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String dd = sdf.format(date);
        if (nowTime == null) {
            nowTime = dd;
        }
        wrapper.lambda().in(DailyLogs::getAdminId, adminId)
                .apply(" date_format(create_time,'%y%mm%dd') = date_format('" + nowTime + "-01','%y%mm%dd')");
        DailyLogs dailyLogs = mapper.selectOne(wrapper);
        if (dailyLogs == null) {
            dailyLogs = new DailyLogs();
            return dailyLogs;
        }
        List<OtherFile> list = fileMapper.selectList(new QueryWrapper<OtherFile>().lambda()
                .eq(OtherFile::getStreamType, 0).eq(OtherFile::getCorrelationId, dailyLogs.getId()));
        if (list == null) {
            list = new ArrayList<>();
        }
        dailyLogs.setOtherFiles(list);
        return dailyLogs;
    }

    @Override
    public DailyLogs showCertainOne(Integer id) {
        DailyLogs dailyLogs = mapper.selectDetail(id);
        //获取附件
        QueryWrapper<OtherFile> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OtherFile::getStreamType, 0).eq(OtherFile::getCorrelationId, id);
        List<OtherFile> list = fileMapper.selectList(wrapper);
        if (list == null) {
            list = new ArrayList<>();
        }
        dailyLogs.setOtherFiles(list);
        //获取评论
        List<Comment> comments = commentService.listComment(id, 26);
        dailyLogs.setComments(comments);
        return dailyLogs;
    }

    @Override
    public Page<DailyLogs> normalList(Integer page, Integer limit, Integer search , String time, Integer type) {
        //如果参数time没传参，默认当前月
        if (StrUtil.isBlank(time)){
            time = DateUtil.format(DateUtil.date(),"yyyy-MM");
        }
        Page<DailyLogs> logsPage = new Page<>(page,limit);
        QueryWrapper<DailyLogs> wrapper = new QueryWrapper<>();
        wrapper.eq(type != null, "M.type", type)
                .eq(search != null, "M.admin_id", search)
                .apply(StrUtil.isNotBlank(time),"LEFT(M.create_time,7)= '" +time+ "'")
                .orderByDesc("M.create_time");
        return mapper.dailyLogsList(logsPage,wrapper);
    }

    @Override
    public Page<DailyLogs> submitList(Integer page, Integer limit, Integer type, String time, Integer adminId) {
        Page<DailyLogs> logsPage = new Page<>(page,limit);
        QueryWrapper<DailyLogs> wrapper = new QueryWrapper<>();
        wrapper.eq(type != null, "M.type", type)
                .eq("M.admin_id", adminId)
                .apply(StrUtil.isNotBlank(time),"LEFT(M.create_time,7)= '" +time+ "'")
                .orderByDesc("M.create_time");
        return mapper.dailyLogsSubmitList(logsPage,wrapper);
    }

    @Override
    public Page<DailyLogs> receptionList(Integer page, Integer limit, Integer type, String time, Integer adminId, Integer search){
        Page<DailyLogs> logsPage = new Page<>(page,limit);
        QueryWrapper<DailyLogs> wrapper = new QueryWrapper<>();
        wrapper.eq(type != null, "M.type", type)
                .eq(adminId != null, "M.reporter_id", adminId)
                .eq(search != null, "M.admin_id", search)
                .apply(StrUtil.isNotBlank(time),"LEFT(M.create_time,7)= '" +time+ "'")
                .orderByDesc("M.create_time");
        return mapper.dailyLogsReceptionList(logsPage,wrapper);
    }

    @Override
    public Map<String, Object> statistics(String time) {
        String time1 = DateUtil.format(new Date(), "yyyy-MM");
        QueryWrapper<DailyLogs> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        if (time1.length() == time.length()) {
            // 某月 日报详情
            wrapper.lambda()
                    .apply(" left(create_time,7) = left('" + time + "',7)");
            Long totalNum = mapper.selectDailyLogsNum(wrapper);
            map.put("total", totalNum);
            //日报数量
            wrapper.clear();
            wrapper.lambda()
                    .eq(DailyLogs::getType, 1)
                    .apply(" left(create_time,7) = left('" + time + "',7)");
            Long dayNum = mapper.selectDailyLogsNum(wrapper);
            map.put("day", dayNum);
            //周报数量
            wrapper.clear();
            wrapper.lambda()
                    .eq(DailyLogs::getType, 2)
                    .apply(" left(create_time,7) = left('" + time + "',7)");
            Long weekNum = mapper.selectDailyLogsNum(wrapper);
            map.put("week", weekNum);
            //月报数量
            wrapper.clear();
            wrapper.lambda()
                    .eq(DailyLogs::getType, 3)
                    .apply(" left(create_time,7) = left('" + time + "',7)");
            Long monthNum = mapper.selectDailyLogsNum(wrapper);
            map.put("month", monthNum);
        } else {
            // 年 日报详情
            Long totalNum = mapper.selectYearDailyLogs(time, null);
            map.put("total", totalNum);
            //日报数量
            Long dayNum = mapper.selectYearDailyLogs(time,1);
            map.put("day", dayNum);
            //周报数量
            Long weekNum = mapper.selectYearDailyLogs(time,2);
            map.put("week", weekNum);
            //月报数量
            Long monthNum = mapper.selectYearDailyLogs(time,3);
            map.put("month", monthNum);
        }
        return map;
    }

}
